<?php
/**
 * Created by PhpStorm.
 * User: xi
 * Date: 2020-04-25
 * Time: 17:08
 */

namespace app\api\service;


class LepayService
{
    // 正式环境地址
    private $url = "https://paygate.leshuazf.com/cgi-bin/lepos_pay_gateway.cgi";

    private $merchant_id = '';
    private $key = '55F92BFFFE64BEB5A78367D60B4B8F94';

    // 交易成功回调地址，如不接收回调不必提供
    private $callback_url = "";
    public function __construct($merchant_id = '', $key = '') {
        if(!empty($merchant_id)){
            $this->merchant_id = $merchant_id;
        }
        if(!empty($key)){
            $this->key = $key;
        }
    }

    public function queryOrder($args){
        $param = array('merchant_id'=>$this->merchant_id,
            'service'=>'query_status',
            'nonce_str'=>$this->nonce_str(),
            'third_order_id'=>$args['order'],
        );

        //request
        $param_str = $this->sign($param);

        //response
        $filecontent = $this->post($this->url, $param_str);
        $re_obj = simplexml_load_string($filecontent);
        return $re_obj;
    }


    public function pay($data = array()){
        $param = array('merchant_id'=>$this->merchant_id,
            'service'=>'get_tdcode',
            'jspay_flag'=>3,
            'body'=>$data['detail'],
            'appid' => 'wx24f19287ae7f5d5e',
            'nonce_str'=>$this->nonce_str(),
            'sub_openid'=>$data['openid'],
            'third_order_id'=>$data['orderNo'],
            'amount'=>$data['amount'],
            'notify_url'=>$data['callback_url'],
            'callback_url'=>$data['callback_url'],
            'pay_way'=>$data['paytype']);

        error_log("=======pay=========".json_encode($param));
        $param_str = $this->sign($param);

        $filecontent = $this->post($this->url, $param_str);
//        $re_obj = simplexml_load_string($filecontent);
        $jsonxml = json_encode(simplexml_load_string($filecontent, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true);
        return $result;
    }


    public function pay2($data = array()){
        $param = array('merchant_id'=>$this->merchant_id,
            'service'=>'get_tdcode',
            'jspay_flag'=>3,
            'appid' => 'wx763ae61820ee8dc5',
            'nonce_str'=>$this->nonce_str(),
            'sub_openid'=>$data['openid'],
            'third_order_id'=>$data['orderNo'],
            'amount'=>$data['pay_price'],
            'notify_url'=>$data['callback_url'],
            'callback_url'=>$data['callback_url'],
            'pay_way'=>'WXZF');

        error_log("=======pay=========".json_encode($param));
        $param_str = $this->sign($param);

        $filecontent = $this->post($this->url, $param_str);
//        $re_obj = simplexml_load_string($filecontent);
        $jsonxml = json_encode(simplexml_load_string($filecontent, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true);
        return $result;
    }

    public function pay3($data = array()){
        $param = array('merchant_id'=>$this->merchant_id,
            'service'=>'get_tdcode',
            'jspay_flag'=>3,
            'appid' => 'wx65bcc9ee84ae5a7c',
            'nonce_str'=>$this->nonce_str(),
            'sub_openid'=>$data['openid'],
            'third_order_id'=>$data['orderNo'],
            'amount'=>$data['pay_price'],
            'notify_url'=>$data['callback_url'],
            'callback_url'=>$data['callback_url'],
            'pay_way'=>'WXZF');

        error_log("=======pay=========".json_encode($param));
        $param_str = $this->sign($param);

        $filecontent = $this->post($this->url, $param_str);
//        $re_obj = simplexml_load_string($filecontent);
        $jsonxml = json_encode(simplexml_load_string($filecontent, 'SimpleXMLElement', LIBXML_NOCDATA));
        $result = json_decode($jsonxml, true);
        return $result;
    }

    /**
     * 被扫支付，刷卡支付
     */
    public function upTdCode($amount, $order_id, $tdcode){
        $param = array('merchant_id'=>$this->merchant_id,
            'service'=>'upload_authcode',
            'pay_way'=>'WXZF',
            'body'=>'支付',
            'auth_code'=>$tdcode,
            'nonce_str'=>$this->nonce_str(),
            'third_order_id'=>$order_id,
            'amount'=>$amount,
            'notify_url'=>$this->callback_url,
            't0'=>0,'callback_url'=>$this->callback_url);
        $param_str = $this->sign($param);

        //response
        $filecontent = $this->post($this->url, $param_str);
        $re_obj = simplexml_load_string($filecontent);
        // var_dump($re_obj);
        return $re_obj;
    }


    //退款
    public function refund($amount, $order_id){
        $param = array('merchant_id'=>$this->merchant_id,
            'service'=>'unified_refund',
            'nonce_str'=>$this->nonce_str(),
            'third_order_id'=>$order_id,
            'refund_amount'=>$amount,
        );

        $param['merchant_refund_id'] = $param['third_order_id'].'T1';
        $param_str = $this->sign($param);

        //response
        $filecontent = $this->post($this->url, $param_str);
        $re_obj = simplexml_load_string($filecontent);
        return $re_obj;
    }

    public function post($url, $data){
        $ch = curl_init();
        $header = array();
        $header[] = 'Content-Type:application/x-www-form-urlencoded';
        curl_setopt($ch, CURLOPT_URL, $this->url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_HEADER, 0);//设定是否输出页面内容
        //curl_setopt($ch,CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1); // post,get 过去
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不验证证书
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1 );
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,10);

        //curl_setopt($ch, CURLOPT_PROXY, '192.168.0.12'); //代理服务器地址
        //curl_setopt($ch, CURLOPT_PROXYPORT, 8888); //代理服务器端口
        $filecontent = curl_exec($ch);
        return $filecontent;
    }

    /**
     * 参数签名
     */
    private function sign($param){
        ksort($param);
        $mparam = $param;
        $queryParam_arr = array();
        foreach($param as $k=>$v){
            $queryParam_arr[] = $k."=".$v;
        }
        $queryParam = implode("&", $queryParam_arr);
        $sign = strtoupper(md5($queryParam.'&key='.$this->key));
        $mqueryParam_arr = array();
        foreach($mparam as $k=>$v){
            $mqueryParam_arr[$k] = $v;
        }
        $mqueryParam_arr['sign'] = $sign;
        return  http_build_query($mqueryParam_arr);
    }

    /**
     *
     */
    private function nonce_str() {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $length = strlen($characters);
        $nonce_str = '';
        for ($i = 0; $i < 16; $i++) {
            $nonce_str .= $characters[rand(0, $length - 1)];
        }
        return $nonce_str;
    }

}